package xyz.chaobei.mall.pojo;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import xyz.chaobei.mall.common.enums.IntEnums;
import xyz.chaobei.mall.model.UmsAdminModel;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * 本地用户实现 spring security 用户detail
 *
 * @author <a href='mailto:maruichao52@gmail.com'>MRC</a>
 * @since 2020/10/19
 */
public class UmsAdminUserDetails implements UserDetails {

    private final UmsAdminModel adminModel;

    private final Set<String> permission;

    public UmsAdminUserDetails(UmsAdminModel adminModel, Set<String> permission) {
        this.adminModel = adminModel;
        this.permission = permission;
    }

    /**
     * <p>构造权限的时候，获取权限列表。并构造进UserDetail
     * <p>author: <a href='mailto:maruichao52@gmail.com'>MRC</a>
     *
     * @return java.util.Collection<? extends org.springframework.security.core.GrantedAuthority>
     * @since 2020/10/22
     **/
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> list = new LinkedList<>();
        for (String per : permission) {
            list.add(new SimpleGrantedAuthority(per));
        }
        return list;
    }

    @Override
    public String getPassword() {
        return adminModel.getPassword();
    }

    @Override
    public String getUsername() {
        return adminModel.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 是否启用
     *
     * @return
     */
    @Override
    public boolean isEnabled() {
        return IntEnums.UMS_ADMIN_UN_LOCK.equals(adminModel.getLock());
    }
}
